package com.group1.bookmanagement.util;

import java.util.HashMap;
import java.util.Map;

/**
 * 图片工具类
 */
public class PhotoUtils {
	
	//大小
	public static final String SIZE = "size";
	//单位
	public static final String UNIT = "unit";
	
	public static double getSize(double size) {
		Map map = convert(size);
		return (double) map.get(SIZE);
	}
	
	public static String getUnit(double size) {
		Map map = convert(size);
		return (String) map.get(UNIT);
	}

    /**
     * 将图片大小转化为合适的单位和大小
     *
     * @param size
     * @return
     */
    public static Map convert(double size) {
        Map<String, Object> map = new HashMap<>();

        int i;
        for (i = 0; i < 3; i++) {
            if (size / 1024 < 1) {
                break;
            }
            size = size / 1024;
        }

        //精确到小数点后两位
        size = Double.parseDouble(String.format("%.2f", size));
        map.put("size", new Double(size));

        switch (i) {
            case 0:
                map.put("unit", "byte");
                break;

            case 1:
                map.put("unit", "KB");
                break;

            case 2:
                map.put("unit", "MB");
                break;

            case 3:
                map.put("unit", "G");
                break;

            default:
                map.put("unit", "byte");
                break;
        }

        return map;
    }
}
